package com.feinno.urcs.group.util;

import com.feinno.cpim.CpimHeader;
import com.feinno.cpim.CpimMessage;
import com.feinno.urcs.types.MobileNo;

import javax.sip.address.SipURI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

/**
 * Created by honghao on 10/23/15.
 */
public class CpimUtils {
	/**
	 *
	 * @param msg
	 * @param fromMobile
	 * @param groupUri
	 * @param contentType
	 * @param isEncode
	 * @return
	 * @throws ParseException
	 */
	public static CpimMessage createCpim(byte[] msg, MobileNo fromMobile, SipURI groupUri, String contentType, boolean isEncode, Date time) throws ParseException {
		CpimMessage cpimMessage = new CpimMessage();
		CpimHeader fromHeader = new CpimHeader(CpimHeader.FROM);
		fromHeader.setValue(fromMobile.toAddress().toString());
		cpimMessage.addHeader(fromHeader);
		CpimHeader toHeader = new CpimHeader(CpimHeader.TO);
		toHeader.setValue(String.format("<%s>", groupUri));
		cpimMessage.addHeader(toHeader);
		CpimHeader datetimeHeader = new CpimHeader(CpimHeader.DATETIME);
		datetimeHeader.setValue(DATETIME_FORMAT.format(time));
		cpimMessage.putHeader(datetimeHeader);
		CpimHeader contentTypeHeader = new CpimHeader(CpimHeader.CONTENT_TYPE);
		contentTypeHeader.setValue(contentType);
		cpimMessage.addHeader(contentTypeHeader);
		if (isEncode) {
			CpimHeader encodeHeader = new CpimHeader("Content-Transfer-Encoding");
			encodeHeader.setValue("base64");
			cpimMessage.addHeader(encodeHeader);
			cpimMessage.setContentByteArray(Base64.getEncoder().encode(msg));
		} else {
			cpimMessage.setContentByteArray(msg);
		}
		return cpimMessage;
	}

	private static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
}
